<?php

/**
 * Classe responsavel por todas as comunidades do sistema.
 * @author Emeson Santana
 * @package app.Controller
 */
Class PostsController extends AppController{
public $helpers = array('Html', 'Form');
	public $name = 'Posts';
	public $uses = array('Post', 'Topic','Community');

	public function add($community_id, $topic_id = null){
		$this->layout = 'ajax';
		$server = $_SERVER['SERVER_NAME']; 
		$endereco = $_SERVER ['REQUEST_URI'];

		if($this->request->is('post')){
			//date_default_timezone_set('America/Recife');
			$this->request->data['Post']['creation_date'] = date("Y-m-d H:i:s");
			if($this->Post->saveAll($this->request->data)){
				$this->Session->setFlash(__('Sucesso!'));
				$this->redirect($this->referer());
			}
			else{
				$this->Session->setFlash(__('Erro!'));
			}
		}
		else{
			$this->request->data['Post']['topic_id'] = $topic_id;
			$this->set('community_id', $community_id);
		}

	}
	public function edit($community_id, $topic_id = null, $id = null){
		$this->layout = 'ajax';
        if ($this->request->is('get')) {
        		$this->Post->id = $id;
				$this->request->data = $this->Post->read();
				$this->set('community_id', $community_id);
				$this->set('topic_id', $topic_id);
		}
		else {
			if ($this->Post->saveAll($this->request->data)) {
				$this->Session->setFlash(__('<span class="label label-success">Sucesso!</span>'));
				$this->redirect('/!'.$this->Community->getUrlById($community_id).'/'.$this->Topic->getUrlById($topic_id));
			}else{
				$this->Session->setFlash(__('<span class="label label-warning">Erro!</span>'));
			}
		}
	}
	public function delete($community_id, $topic_id, $id){

		if (!$this->request->is('post')) {
            throw new MethodNotAllowedException();
        }
        $this->Post->id = $id;
        if (!$this->Post->exists()) {
            throw new NotFoundException(__('Invalid post'));
        }
        if ($this->Post->delete()) {
            $this->Session->setFlash(__('<span class="label label-success">Sucesso!</span>'));
            $this->redirect('/!'.$this->Community->getUrlById($community_id).'/'.$this->Topic->getUrlById($topic_id));
        }
        $this->Session->setFlash(__('<span class="label label-warning">Erro!</span>'));
        $this->redirect('/!'.$this->Community->getUrlById($community_id).'/'.$this->Topic->getUrlById($topic_id));
		
	}

}